﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using WeChatSDK.WeChatDto;

namespace WeChatSDK.Common
{
    /// <summary>
    /// Dto扩展
    /// </summary>
    public static class DtoExtension
    {
        public static Dictionary<string,object> ToDictionary(this object source,bool snakeCase = false) 
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            Type type = source.GetType();
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach(PropertyInfo propertyInfo in propertyInfos)
            {
                MethodInfo methodInfo = propertyInfo.GetMethod;
                if (methodInfo != null&& methodInfo.IsPublic)
                {
                    if(methodInfo.Invoke(source,new object[] { }) != null)
                    {
                        string name = propertyInfo.Name;
                        if (snakeCase)
                        {
                            name = SnakeCase(name);
                        }
                        dictionary.Add(name, methodInfo.Invoke(source, new object[] { }));
                    }
                }
            }
            return dictionary;
        }

        private static string SnakeCase(string value)
        {
            Regex regex = new Regex("[A-Z]");

            while (regex.IsMatch(value))
            {
                Match match = regex.Match(value);
                value = value.Replace(match.Value, "_" + match.Value.ToLower());
            }
            return value.TrimStart('_');
        }
    }
}
